package com.ruiao.car.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Configuration
public class GlobalFilter {


    @Bean
    public FilterRegistrationBean filterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new ServletWrapperFilter());//添加过滤器
        registration.addUrlPatterns("/*");//设置过滤路径，/*所有路径
        registration.setName("ServletWrapperFilter");
        registration.setOrder(1);//设置优先级
        return registration;
    }

    public class ServletWrapperFilter implements Filter {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            //LoginInterceptor在做安全验证时调用了request.getReader()导致@RequestBody无法获取数据（getReader只能调用一次）
            //所以在这里将数据包装到二进制数组里
            ServletRequest requestWrapper = null;
            HttpServletRequest servletRequest = (HttpServletRequest)request;
            //base64不处理，否则会字符串太长报错
            if (request instanceof HttpServletRequest && "POST".equals( ((HttpServletRequest) request).getMethod())
                    &&  servletRequest.getRequestURL().indexOf("base64")==-1 ) {
                requestWrapper = new com.ruiao.car.config.ServletRequestWrapper((HttpServletRequest) request);

                filterChain.doFilter(requestWrapper, response);
            }else{
                filterChain.doFilter(request, response);
            }
        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void destroy() {
        }


    }
}
